define(["jquery", "easy-admin","xm-select"], function ($, ea) {

    var form =layui.form;
    var mid =$("#mid").val();
    var type =$("#type").val();
    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: 'mall.goods/index?type='+type+'&id='+mid,
        add_url: 'mall.goods/add?type='+type+'&id='+mid,
        edit_url: 'mall.goods/edit?type='+type,
        delete_url: 'mall.goods/delete',
        export_url: 'mall.goods/export',
        modify_url: 'mall.goods/modify',
        stock_url: 'mall.goods/stock',
    };

    var Controller = {

        index: function () {
            ea.table.render({
                init: init,
                height:'full-50',
                toolbar: ['refresh',
                    [{
                        text: '添加',
                        url: init.add_url,
                        method: 'open',
                        auth: 'add',
                        class: 'layui-btn layui-btn-normal layui-btn-sm',
                        icon: 'fa fa-plus ',
                        extend: 'data-full="true"',
                    }],
                    'delete', 'export'],
                cols: [[
                    {type: "checkbox"},
                    {field: 'id', width: 80, title: 'ID'},
                    {field: 'sort', width: 80, title: '排序', edit: 'text'},
                    {field: 'cate.title', width: 150, title: '商品分类'},
                    {field: 'title', width: 250, title: '商品名称'},
                    {field: 'logo', width: 80, title: '商品图片', search: false, templet: ea.table.image},
                    {field: 'market_price', width: 100, title: '市场价', templet: ea.table.price,search: false},
                    {field: 'goods_price', width: 100, title: '销售价', templet: ea.table.price,search: false},
                    {field: 'cost_price', width: 100, title: '结算价', templet: ea.table.price,search: false},
                    {field: 'total_stock', width: 100, title: '库存统计'},
                    {field: 'stock', width: 100, title: '剩余库存'},
                    {field: 'sales', width: 100, title: '销量'},
                    {field: 'islimit', title: '限购', width: 120,search: 'select', selectList: {0: '非限购商品', 1: '限购商品'}},
                    {field: 'status', title: '状态', width: 120, selectList: {0: '下架', 1: '上架'}, templet: ea.table.switch},
                    {field: 'create_time', width: 180, title: '创建时间', search: 'range'},
                    {
                        width: 250,
                        title: '操作',
                        templet: ea.table.tool,
                        operat: [
                            [{
                                text: '编辑',
                                url: init.edit_url,
                                method: 'open',
                                auth: 'edit',
                                class: 'layui-btn layui-btn-xs layui-btn-success',
                                extend: 'data-full="true"',
                            }],
                            'delete']
                    }
                ]],
            });

            ea.listen();
        },
        add: function () {


            form.on('radio(islimit)', function (data) {
                if(data.value==1){
                    $("#limitnum").show();
                    $("#perlimitnum").show();
                }else{
                    $("#limitnum").hide();
                    $("#perlimitnum").hide();
                }
                console.log(data.value); //被点击的 radio 的 value 值
            });

            var demo1 = xmSelect.render({
                el: '#goodstags',
                on: function (data) {
                    var arr = data.arr;

                    let ids=[];
                    if (arr.length > 0) {
                        for (let i = 0; i < arr.length; i++) {
                            ids.push(arr[i].value);
                            $("#tag_ids").val(ids);
                        }
                    }
                },
                autoRow: true,
                toolbar: { show: true },
                filterable: true,
                remoteSearch: true,

                remoteMethod: function(val, cb, show){
                    $.ajax({
                        type: "GET",
                        url: "/admin/mall.tags/getCateByList",
                        data: {keyword: val},
                        dataType: "json",
                        success: function (data) {
                            console.log(data);
                            cb(data.data);
                        }
                    })
                }
            })
            loadingdemo2();
            function loadingdemo2(){
                var demo2 = xmSelect.render({
                    el: '#goodsdoors',
                    on: function (data) {
                        var arr = data.arr;

                        let ids=[];
                        if (arr.length > 0) {
                            for (let i = 0; i < arr.length; i++) {
                                ids.push(arr[i].value);
                                $("#door_ids").val(ids);
                            }
                        }
                    },
                    autoRow: true,
                    toolbar: { show: true },
                    filterable: true,
                    remoteSearch: true,
                    remoteMethod: function(val, cb, show){
                        var managerids =$("#managerids").val();
                        var manager_id =$("#manager_id").val();
                        if(managerids>0){
                            manager_id=managerids;
                        }
                        $.ajax({
                            type: "GET",
                            url: "/admin/mall.door/getDoorByList",
                            data: {keyword: val,manager_id:manager_id},
                            dataType: "json",
                            success: function (data) {
                                console.log(data);
                                cb(data.data);
                            }
                        })
                    }
                })
            }
            layui.use(['layer', 'jquery', 'form'], function () {
                var layer = layui.layer,
                    $ = layui.jquery;
                form = layui.form;

                form.on('select(manager)', function(data){
                    console.log(data.value);
                    loadingdemo2();
                })
            })

            function createSkuTable(url = '') {
                var specData = [];
                $.each($('#spec-table tbody tr'), function () {
                    var child = [];
                    $.each($(this).find('input[type=checkbox]'), function () {
                        child.push({id: $(this).val(), title: $(this).attr('title'), checked: $(this).is(':checked')});
                    });
                    var specItem = {
                        id: $(this).find('td').eq(0).attr('data-id'),
                        title: $(this).find('td').eq(0).text(),
                        show: $(this).find('input[type=checkbox]:checked').length > 0,
                        child: child
                    };
                    specData.push(specItem);
                });

                if ($('#spec-table tbody input[type=checkbox]:checked').length) {
                    $('#sku-table').parent().parent().removeClass('layui-hide');

                    var prependThead = [], prependTbody = [];
                    $.each(specData, function () {
                        if (this.show) {
                            prependThead.push(this.title);
                            var prependTbodyItem = [];
                            $.each(this.child, function () {
                                if (this.checked) {
                                    prependTbodyItem.push({id: this.id, title: this.title});
                                }
                            });
                            prependTbody.push(prependTbodyItem);
                        }
                    });
                    if (prependThead.length > 0) {
                        $('#sku-table thead').html('<tr>' +
                            prependThead.map(function (t, i, a) {
                                return '<th>' + t + '</th>'
                            }) +
                            '<th>图片</th>' +
                            '<th>销售价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                            '<th>市场价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                            '<th>成本价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                            '<th>库存 <i class="layui-icon layui-icon-cols"></i></th>' +
                            '<th>状态 </th>' +
                            '</tr>');
                    }

                    var prependTbodyTrs = [];
                    prependTbody.reduce(function (prev, cur, index, array) {
                        var tmp = [];
                        prev.forEach(function (a) {
                            cur.forEach(function (b) {
                                tmp.push({id: a.id + '-' + b.id, title: a.title + '-' + b.title});
                            })
                        });
                        return tmp;
                    }).forEach(function (item, index, array) {
                        prependTbodyTrs.push('<tr>' +
                            item.title.split('-').map(function (t, i, a) {
                                return '<td>' + t + '</td>';
                            }) +
                            '<td><input type="hidden" name="skus[' + item.id + '][picture]" value=""><img src="/static/img/sku-add.png" alt="sku图片"></td>' +
                            '<td><input type="text" name="skus[' + item.id + '][price]" value="0" class="layui-input" lay-verify="required|number" lay-reqtext="销售价不能为空"></td>' +
                            '<td><input type="text" name="skus[' + item.id + '][market_price]" value="0" class="layui-input" lay-verify="required|number" lay-reqtext="市场价不能为空"></td>' +
                            '<td><input type="text" name="skus[' + item.id + '][cost_price]" value="0" class="layui-input" lay-verify="required|number" lay-reqtext="成本价不能为空"></td>' +
                            '<td><input type="text" name="skus[' + item.id + '][stock]" value="0" class="layui-input" lay-verify="required|number" lay-reqtext="库存不能为空"></td>' +
                            '<td><select name="skus[' + item.id + '][status]"><option value="1">启用</option><option value="0">禁用</option></select></td>' +
                            '</tr>');
                    });
                    if (prependTbodyTrs.length > 0) {
                        $('#sku-table tbody').html(prependTbodyTrs.join(''));
                        $('input[name=spec]').val(JSON.stringify(specData));
                        form.render('select');
                        upload.render({
                            elem: '#sku-table td img',
                            url: url,
                            exts: 'png|jpg|ico|jpeg|gif',
                            accept: 'images',
                            acceptMime: 'image/*',
                            multiple: false,
                            done: function (res) {
                                if (res.code === 1) {
                                    var url = res.data.url;
                                    $(this.item).attr('src', url).prev().val(url);
                                    layer.msg(res.msg);
                                } else {
                                    layer.msg(res.msg);
                                }
                                return false;
                            }
                        });
                    }
                } else {
                    $('#sku-table').parent().parent().addClass('layui-hide');
                    $('#sku-table thead').html('');
                    $('#sku-table tbody').html('');
                    $('input[name=spec]').val('');
                }
            }

            /**
             * 初始化sku表
             */
            createSkuTable('/admin/ajax/upload');

            /**
             * 监听sku表变化
             */
            form.on('checkbox(filter)', function (data) {
                createSkuTable('/admin/ajax/upload');
            });
            form.on('radio(cate)', function (data) {

                if (data.value == 0) {
                    $(".specs_one").slideDown();
                    $(".specs_two").slideUp();
                } else {
                    $(".specs_one").slideUp();
                    $(".specs_two").slideDown();
                }
            });
            /**
             * 监听批量赋值
             */
            $(document).on('click', '#sku-table thead tr th i', function () {
                var that = this;
                layer.prompt(function (value, index, elem) {
                    $.each($('#sku-table tbody tr'), function () {
                        $(this).find('td').eq($(that).parent().index()).children('input').val(value);
                    });
                    layer.close(index);
                });
            });


            ea.listen();
        },
        edit: function () {
            form.on('radio(islimit)', function (data) {
                if(data.value==1){
                    $("#limitnum").show();
                    $("#perlimitnum").show();
                }else{
                    $("#limitnum").hide();
                    $("#perlimitnum").hide();
                }
                console.log(data.value); //被点击的 radio 的 value 值
            });
            var demo1 = xmSelect.render({
                el: '#goodstags',
                on: function (data) {
                    var arr = data.arr;

                    let ids=[];
                    if (arr.length > 0) {
                        for (let i = 0; i < arr.length; i++) {
                            ids.push(arr[i].value);
                            $("#tag_ids").val(ids);
                        }
                    }
                },
                autoRow: true,
                toolbar: { show: true },
                filterable: true,
                remoteSearch: true,
                remoteMethod: function(val, cb, show){
                    $.ajax({
                        type: "GET",
                        url: "/admin/mall.tags/getCateByList",
                        data: {keyword: val},
                        dataType: "json",
                        success: function (data) {
                            console.log(data);
                            cb(data.data);
                        }
                    })
                }
            });
            loadingdemo2();
            function loadingdemo2(){
                var demo2 = xmSelect.render({
                    el: '#goodsdoors',
                    on: function (data) {
                        var arr = data.arr;
                        let ids=[];
                        if (arr.length > 0) {
                            for (let i = 0; i < arr.length; i++) {
                                ids.push(arr[i].value);
                                $("#door_ids").val(ids);
                            }
                        }
                    },
                    autoRow: true,
                    toolbar: { show: true },
                    filterable: true,
                    remoteSearch: true,
                    remoteMethod: function(val, cb, show){
                        var manager_id =$("#manager_id").val();
                        var managerids =$("#managerids").val();
                        var type =$("#type").val();
                        if(type>0){
                            manager_id =managerids;
                        }
                        $.ajax({
                            type: "GET",
                            url: "/admin/mall.door/getDoorByList",
                            data: {keyword: val,manager_id:manager_id},
                            dataType: "json",
                            success: function (data) {
                                console.log(data);
                                cb(data.data);
                            }
                        })
                    }
                })
                console.log($("#goods_id").val());
                ea.request.post(
                    {
                        url: '/admin/mall.goods/getInfo?id='+$("#goods_id").val(),
                    }, function (res) {
                        console.log(res)
                        if(res.code == 1){
                            demo1.setValue(res.data.tags);
                            demo2.setValue(res.data.doors);
                        }
                    }
                );
            }
            layui.use(['layer', 'jquery', 'form'], function () {
                var layer = layui.layer,
                    $ = layui.jquery;
                form = layui.form;
                form.on('select(manager)', function(data){
                    console.log(data.value);
                    loadingdemo2();
                })
            })
            /**
             * 初始化intvalue表
             */
            $.post(
                {
                    url: '/admin/mall.goods/getGoodscates?id='+$("#goods_id").val(),
                }, function (res) {
                    if(res.code == 1){
                        createSkuTable('/admin/ajax/upload',res.data.sku_data,1);
                    }
                }
            );
            function createSkuTable(url = '',array_item = [],array_type=0) {
                var specData = [];
                $.each($('#spec-table tbody tr'), function () {
                    var child = [];
                    $.each($(this).find('input[type=checkbox]'), function () {
                        child.push({
                            id: $(this).val(),
                            title: $(this).attr('title'),
                            checked: $(this).is(':checked')
                        });
                    });
                    var specItem = {
                        id: $(this).find('td').eq(0).attr('data-id'),
                        title: $(this).find('td').eq(0).text(),
                        show: $(this).find('input[type=checkbox]:checked').length > 0,
                        child: child
                    };
                    specData.push(specItem);
                });

                if ($('#spec-table tbody input[type=checkbox]:checked').length) {
                    $('#sku-table').parent().parent().removeClass('layui-hide');

                    var prependThead = [], prependTbody = [];
                    $.each(specData, function () {
                        if (this.show) {
                            prependThead.push(this.title);
                            var prependTbodyItem = [];
                            $.each(this.child, function () {
                                if (this.checked) {
                                    prependTbodyItem.push({id: this.id, title: this.title});
                                }
                            });
                            prependTbody.push(prependTbodyItem);
                        }
                    });
                    if (prependThead.length > 0) {
                        $('#sku-table thead').html('<tr>' +
                            prependThead.map(function (t, i, a) {
                                return '<th>' + t + '</th>'
                            }) +
                            '<th>图片</th>' +
                            '<th>销售价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                            '<th>市场价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                            '<th>成本价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                            '<th>库存 <i class="layui-icon layui-icon-cols"></i></th>' +
                            +
                                '</tr>');
                    }

                    var prependTbodyTrs = [];
                    prependTbody.reduce(function (prev, cur, index, array) {
                        var tmp = [];
                        prev.forEach(function (a) {
                            cur.forEach(function (b) {
                                tmp.push({id: a.id + '-' + b.id, title: a.title + '-' + b.title});
                            })
                        });
                        return tmp;
                    }).forEach(function (item, index, array) {
                        if(array_type == 1){
                            prependTbodyTrs.push('<tr>' +
                                item.title.split('-').map(function (t, i, a) {
                                    return '<td>' + t + '</td>';
                                })+
                                '<td><input type="hidden" name="skus[' + item.id + '][picture]" value="'+array_item[item.id].image+'"><img src="'+array_item[item.id].image+'" alt="sku图片" style="width: 20px"></td>' +
                                '<td><input type="text" name="skus[' + item.id + '][price]" value="'+array_item[item.id].price+'" class="layui-input" lay-verify="required|number" lay-reqtext="销售价不能为空"></td>' +
                                '<td><input type="text" name="skus[' + item.id + '][market_price]" value="'+array_item[item.id].market_price+'" class="layui-input" lay-verify="required|number" lay-reqtext="市场价不能为空"></td>' +
                                '<td><input type="text" name="skus[' + item.id + '][cost_price]" value="'+array_item[item.id].cost_price+'" class="layui-input" lay-verify="required|number" lay-reqtext="成本价不能为空"></td>' +
                                '<td><input type="text" name="skus[' + item.id + '][stock]" value="'+array_item[item.id].stock+'" class="layui-input" lay-verify="required|number" lay-reqtext="库存不能为空"></td>' +

                                '</tr>');
                        }else{
                            prependTbodyTrs.push('<tr>' +
                                item.title.split('-').map(function (t, i, a) {
                                    return '<td>' + t + '</td>';
                                })+
                                '<td><input type="hidden" name="skus[' + item.id + '][picture]" value=""><img src="/static/img/sku-add.png" alt="sku图片"></td>' +
                                '<td><input type="text" name="skus[' + item.id + '][price]" value="0" class="layui-input" lay-verify="required|number" lay-reqtext="销售价不能为空"></td>' +
                                '<td><input type="text" name="skus[' + item.id + '][market_price]" value="0" class="layui-input" lay-verify="required|number" lay-reqtext="市场价不能为空"></td>' +
                                '<td><input type="text" name="skus[' + item.id + '][cost_price]" value="0" class="layui-input" lay-verify="required|number" lay-reqtext="成本价不能为空"></td>' +
                                '<td><input type="text" name="skus[' + item.id + '][stock]" value="0" class="layui-input" lay-verify="required|number" lay-reqtext="库存不能为空"></td>' +

                                '</tr>');
                        }

                    });
                    if (prependTbodyTrs.length > 0) {
                        $('#sku-table tbody').html(prependTbodyTrs.join(''));
                        $('input[name=spec]').val(JSON.stringify(specData));
                        form.render('select');
                        upload.render({
                            elem: '#sku-table td img',
                            url: url,
                            exts: 'png|jpg|ico|jpeg|gif',
                            accept: 'images',
                            acceptMime: 'image/*',
                            multiple: false,
                            done: function (res) {
                                if (res.code === 1) {
                                    var url = res.data.url;
                                    $(this.item).attr('src', url).prev().val(url);
                                    layer.msg(res.msg);
                                } else {
                                    layer.msg(res.msg);
                                }
                                return false;
                            }
                        });
                    }
                } else {
                    $('#sku-table').parent().parent().addClass('layui-hide');
                    $('#sku-table thead').html('');
                    $('#sku-table tbody').html('');
                    $('input[name=spec]').val('');
                }
            }



            /**
             * 监听sku表变化
             */
            form.on('checkbox(filter)', function (data) {
                createSkuTable('/admin/ajax/upload');
            });
            form.on('radio(cate)', function (data) {

                if (data.value == 0) {
                    $(".specs_one").slideDown();
                    $(".specs_two").slideUp();
                } else {
                    $(".specs_one").slideUp();
                    $(".specs_two").slideDown();
                }
            });
            /**
             * 监听批量赋值
             */
            $(document).on('click', '#sku-table thead tr th i', function () {
                var that = this;
                layer.prompt(function (value, index, elem) {
                    $.each($('#sku-table tbody tr'), function () {
                        $(this).find('td').eq($(that).parent().index()).children('input').val(value);
                    });
                    layer.close(index);
                });

            });
            layui.form.render()
            ea.listen();
        },
        dialog: function () {

            let isInputVal = false
            var cls = '' //点击时父级的class
            let moke = [];

            let request = getRequest();

            cls = request['cls'];

            function queryClassif() { // 请求分类 后端接口

                let html = ''
                ea.request.post(
                    {
                        url: '/admin/mall.specs/getSpecsList',
                    }, function (res) {
                        res.data.forEach(function (item, index) {
                            html += `<li class="child-ele" data-id="${item.id}"  data-index="${index}">${item.title}</li>`
                        })
                        $('.spec-left').html(html)
                    }
                );
            }

            queryClassif(); // 获取后端分类数据

            //  点击获取而已
            $('body').on('click', '.child-ele', function () {

                $(this).parent().children('li').removeClass('layui-btn-normal');
                $(this).addClass('layui-btn-normal');

                let index = $(this).attr('data-index');
                specs_id = $(this).attr('data-id');
                // let projectArr = moke[index]['project'].split(',')

                let url = "/admin/mall.specsValue/getBySpecsId" + "?specs_id=" + specs_id;

                ea.request.get({
                    url: url
                }, function (res) {
                    let html = ''
                    let projectArr = res.data;
                    projectArr.forEach(function (item) {
                        html += '<button type="button" data-specs-value-id="' + item.id + '" class="layui-btn layui-btn-sm layui-btn-normal" style="margin-top: 12px"> <b>' + item.title + '</b><i class="layui-icon del-child-tags" style="padding-left: 12px;"></i></button>'
                    })
                    $specleft = $('.spec-right')
                    $($specleft).html(html)
                });

                isInputVal = true

            })

            // 删除规格值按钮
            $('html').on('click', '.del-child-tags', function () {
                $(this).parent().remove()
                // var index = parent.layer.getFrameIndex(window.name);
                // parent.layer.close(index);
            })

            // 添加规格标签
            $('#add-spec-tags').on('keypress', function (e) {
                console.log(e);
                if (!isInputVal) {
                    return layer.msg('请点选左侧规格名称')
                }
                if (e.which === 13) {
                    let tags = $(this).val();
                    tags = tags.replace(/\-/g,"~");
                    let url = "/admin/mall.specsValue/save?specs_id=" + specs_id + "&name=" + tags;
                    ea.request.get({
                        url: url
                    }, function (res) {
                        if (res.code != 1) {
                            layer.msg("添加失败，请稍候重试");
                            return false;
                        }
                        let tag = '<button type="button" data-specs-value-id="' + res.data.id + '" class="layui-btn layui-btn-sm layui-btn-normal" style="margin-top: 12px"><b>' + tags + '</b> <i class="layui-icon del-child-tags" style="padding-left: 12px;"></i></button>'
                        $('.spec-right').append(tag)
                        $(this).val('');
                    });

                }
            })


            // 提交规格值到商品页面
            $('html').on('click', '.classify-btn', function () {
                let spec_left_name = '';
                let spec_left_id = 0;
                // 左侧规格类目
                let spec_left = $('.spec-left').children('li')
                spec_left.each(function (index, item) {
                    if ($(item).hasClass('layui-btn-normal')) {
                        spec_left_name = $(item).text()
                        spec_left_id = $(item).attr('data-id')
                    }
                })

                // 右侧规格值
                let spec_right = $('.spec-right').find('button')
                let tmp = ''
                let spec_tmp = ''

                spec_right.each(function (index, item) {
                    let name = $(item).children('b').text()
                    let specs_value_id = $(item).attr('data-specs-value-id');
                    tmp += `<li class="layui-badge layui-bg-blue">${name}</li>`
                    //spec_tmp += `<li><label><input type="checkbox"  class="sku_value" lay-ignore  propvalid="${specs_value_id}" value="${name}"/>${name}</label></li>`
                    spec_tmp += `<input type="checkbox" title="${name}" lay-filter="filter" value="${specs_value_id}">`
                });
                // 给父级 赋值
                parent.$('.' + cls).find('input').val(spec_left_name)
                parent.$('.' + cls).find('input').attr('data-id', spec_left_id);
                parent.$('.' + cls).find('input').attr('data-name', spec_left_name);
                parent.$('.' + cls).find('ul').html(tmp);

                if (spec_tmp == '') {
                    layer.msg("请选择规格值", {
                        icon: 5, shade: 0.5
                    });
                    return false;
                }
                let conf = `<tr>
                            <td data-id="${spec_left_id}">${spec_left_name}</td>
                            <td>
                                ${spec_tmp}
                            </td>
                        </tr>`

                parent.$('.skus-warp').append(conf)
                // window.parent.location.reload();//刷新父页面
                var index = parent.layer.getFrameIndex(window.name);
                parent.layui.form.render();

                parent.layer.close(index);
            })

            function getRequest() {
                let url = location.search; //获取url中"?"符后的字串
                let theRequest = {};
                if (url.indexOf("?") != -1) {
                    var str = url.substr(1);
                    strs = str.split("&");
                    for (var i = 0; i < strs.length; i++) {
                        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                    }
                }
                return theRequest;
            }

            ea.listen();
        },

    };
    return Controller;
});